﻿using System;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
using System.Linq;
using System.Text;
using static System.Net.Mime.MediaTypeNames;
using Xc.DataAccess.Core;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Windows.Forms;

namespace Xc.DataAccess.HyperTerminalCore.Models
{
    /// <summary>
    /// TCP客户端信息
    /// </summary>
    public class TcpClientInfo : ClientInfo<TcpClientInfo>, ITcpClientInfo
    {
        public TcpClientInfo(TcpClient tcpClient,Encoding encoding):base(encoding)
        {
            TcpClient = tcpClient;
            SetIpAddress(tcpClient.Client);
        }
        /// <summary>
        /// TCP客户端
        /// </summary>
        public TcpClient TcpClient { get; private set; }

        protected override async void ReceiveData()
        {
            await Task.Factory.StartNew(async () =>
            {
                Token.Cancel();
                await Task.Delay(100);
                Token = new CancellationTokenSource();
                var stream = TcpClient.GetStream();
                while (!Token.IsCancellationRequested)
                {
                    try
                    {

                        byte[] buffer = new byte[40906];
                        var length = await stream.ReadAsync(buffer, 0, buffer.Length);
                        if (length > 0)
                        {

                            ReceiveCount += length;
                            var data = buffer.Take(length).ToArray();
                            if (UseReceive == false)
                            {
                                receiveBuffer.Enqueue(data);
                            }
                            else
                            {
                                RaisedReceiveMessage(data, this);
                            }
                        }
                        else
                        {
                           this.Close();
                            break;
                        }
                        if (TcpClient.Available==0)
                        {
                            await Task.Delay(100);
                        }
                        else
                        {
                            await Task.Delay(5);
                        }
                    }
                    catch (Exception err)
                    {
                        Close();
                        break;
                    }

                }
            });

        }
        /// <summary>
        /// 发送字节码数据
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public override async Task<Result> Send(byte[] buffer)
        {
            if ((buffer == null) || (buffer.Length == 0))
            {
                return Result.Reject("输入数据无效，无法发送");
            }

            try
            {

                var stream = TcpClient.GetStream();
                await stream.WriteAsync(buffer);
                SendCount += buffer.Length;
                return Result.Accept("发送成功");
            }
            catch (Exception err)
            {

                return Result.Reject(err.Message);

            }

        }
        /// <summary>
        /// 关闭通道
        /// </summary>
        public override void Close()
        {
            base.Close();
            RaisedClose(this);
            TcpClient.Close();
        }

    }
}
